import java.io.IOException;
import java.io.StringReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Creat with IntelliJ IDEA
 * Description
 * User: mamba24
 * Date: 2022-08-06
 * Time: 14:44
 * To BE A Better Person-2020-3-2
 */
public class UdpEchoServer {
    //启动Udp首先要打开一个socket文件
    public static DatagramSocket socket=null;
    public UdpEchoServer(int port) throws SocketException {
        //绑定一个端口号
        socket=new DatagramSocket(port);
    }
    //启动一个服务器
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true){
            //1.读取客户端发来的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            //2.对请求进行解析。把DatagramPacket转成以一个String
            String request=new String(requestPacket.getData(),0, requestPacket.getLength());
            //3.根据请求，处理响应
            //因为是回显服务器，所以这个也可以不这么写，但是process里面是完成逻辑的，所以后面的代码要这么写
            String respons=process(request);
            //4.把响应构造成DatagramPacket对象。
            //解析：respons.getBytes()将字符集转化为字节序列
            DatagramPacket responsPacket = new DatagramPacket(respons.getBytes(),respons.getBytes().length,requestPacket.getSocketAddress());
            //5.将DatagramPacket 返回给对象
            socket.send(responsPacket);
            System.out.printf("[%s:%d]  req=%s;resp=%s\n",requestPacket.getAddress().toString(),requestPacket.getPort(),request,responsPacket);
        }
    }
    public String process(String req){
        return req;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server=new UdpEchoServer(8888);
        server.start();
    }
}
